package handlers

import (
	"backEnd/database"
	"backEnd/models"
	"backEnd/utils"
	"database/sql"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// GetSubjectList 获取推荐专题列表
func GetSubjectList(c *gin.Context) {
	startTime := time.Now()

	pageNum, _ := strconv.Atoi(c.DefaultQuery("pageNum", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "5"))
	offset := (pageNum - 1) * pageSize

	query := `
		SELECT s.id, s.theme, s.day, s.view_count, s.size,
		       GROUP_CONCAT(
		           CONCAT('{"_id":"', sw.wallpaper_id, '","smallPicurl":"', w.small_picurl, '"}')
		           ORDER BY sw.sort SEPARATOR '|||'
		       ) as pic_list
		FROM subject s
		LEFT JOIN subject_wallpaper sw ON s.id = sw.subject_id
		LEFT JOIN wallpaper w ON sw.wallpaper_id = w.id
		WHERE s.checked = 1
		GROUP BY s.id, s.theme, s.day, s.view_count, s.size
		ORDER BY s.create_time DESC
		LIMIT ? OFFSET ?
	`

	rows, err := database.DB.Query(query, pageSize, offset)
	if err != nil {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "查询失败",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}
	defer rows.Close()

	var subjects []models.Subject
	for rows.Next() {
		var subject models.Subject
		var picListStr sql.NullString

		err := rows.Scan(&subject.ID, &subject.Theme, &subject.Day, &subject.ViewCount, &subject.Size, &picListStr)
		if err != nil {
			continue
		}

		// 解析picList（简化处理，实际可能需要更复杂的JSON解析）
		if picListStr.Valid {
			// 这里简化处理，实际应该解析JSON
			subject.PicList = []models.SubjectPicItem{}
		}

		subjects = append(subjects, subject)
	}

	// 获取每个专题的图片列表
	for i := range subjects {
		picQuery := `
			SELECT sw.wallpaper_id, w.small_picurl
			FROM subject_wallpaper sw
			JOIN wallpaper w ON sw.wallpaper_id = w.id
			WHERE sw.subject_id = ?
			ORDER BY sw.sort ASC
			LIMIT 3
		`
		picRows, _ := database.DB.Query(picQuery, subjects[i].ID)
		var picList []models.SubjectPicItem
		for picRows.Next() {
			var picItem models.SubjectPicItem
			picRows.Scan(&picItem.ID, &picItem.SmallPicURL)
			picList = append(picList, picItem)
		}
		picRows.Close()
		subjects[i].PicList = picList
	}

	c.JSON(http.StatusOK, models.Response{
		ErrCode:  0,
		ErrMsg:   "查询成功",
		Data:     subjects,
		TimeCost: time.Since(startTime).Milliseconds(),
	})
}

// GetSubjectDetail 获取推荐专题详情
func GetSubjectDetail(c *gin.Context) {
	startTime := time.Now()

	subjectID := c.Query("id")
	if subjectID == "" {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "专题ID不能为空",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}

	// 查询专题基本信息
	query := `
		SELECT id, theme, description, day, view_count, size, type, user_id, checked, create_time
		FROM subject
		WHERE id = ?
	`

	var subject models.Subject
	var checked int
	err := database.DB.QueryRow(query, subjectID).Scan(
		&subject.ID, &subject.Theme, &subject.Description, &subject.Day, &subject.ViewCount, &subject.Size,
		&subject.Type, &subject.UserID, &checked, &subject.CreateTime,
	)

	if err != nil {
		c.JSON(http.StatusOK, models.Response{
			ErrCode:  400,
			ErrMsg:   "查询失败",
			Data:     nil,
			TimeCost: time.Since(startTime).Milliseconds(),
		})
		return
	}

	subject.Checked = checked == 1

	// 增加阅读次数
	updateQuery := "UPDATE subject SET view_count = view_count + 1 WHERE id = ?"
	database.DB.Exec(updateQuery, subjectID)

	// 查询专题下的壁纸列表
	picQuery := `
		SELECT w.id, w.small_picurl, w.score, w.view_count, w.checked, w.description,
		       wc.name as classname, w.classid, w.nickname,
		       GROUP_CONCAT(wt.tag_name ORDER BY wt.tag_name SEPARATOR ',') as tags
		FROM subject_wallpaper sw
		JOIN wallpaper w ON sw.wallpaper_id = w.id
		LEFT JOIN wallpaper_classify wc ON w.classid = wc.id
		LEFT JOIN wallpaper_tag wt ON w.id = wt.wallpaper_id
		WHERE sw.subject_id = ?
		GROUP BY w.id, w.small_picurl, w.score, w.view_count, w.checked, w.description, wc.name, w.classid, w.nickname
		ORDER BY sw.sort ASC
	`

	picRows, err := database.DB.Query(picQuery, subjectID)
	if err == nil {
		defer picRows.Close()

		var picList []models.SubjectPicItem
		for picRows.Next() {
			var picItem models.SubjectPicItem
			var tabsStr sql.NullString
			var score sql.NullFloat64
			var checked int

			err := picRows.Scan(&picItem.ID, &picItem.SmallPicURL, &score, &picItem.ViewCount, &checked, &picItem.Description,
				&picItem.ClassName, &picItem.ClassID, &picItem.Nickname, &tabsStr)
			if err != nil {
				continue
			}

			picItem.Checked = checked == 1
			if score.Valid {
				picItem.Score = utils.FormatFloat(score.Float64)
			}

			if tabsStr.Valid {
				picItem.Tabs = utils.ParseTabsString(tabsStr.String)
			}

			picList = append(picList, picItem)
		}
		subject.PicList = picList
	}

	c.JSON(http.StatusOK, models.Response{
		ErrCode:  0,
		ErrMsg:   "查询成功",
		Data:     subject,
		TimeCost: time.Since(startTime).Milliseconds(),
	})
}
